/**   
 * @Title: SportteryBasketballAgp.java 
 * @Package com.esun.rabbit2.viewer.mainact.lotteryhallact 
 * @Description: (竞彩足球ActivityGroup) 
 * @author: City Jiangsy@500wan.com   
 * @date: 2011-8-12 上午10:32:09  
 * Copyright: (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.lotteryhallact;

import java.util.Calendar;
import java.util.Hashtable;

import android.app.ActivityGroup;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.model.ServerCurrentTimeInfo;
import com.esun.model.UserInfo;
import com.esun.rabbit2.communicaters.lotteryinfo.GetServerTimeCommunicater;
import com.esun.rabbit2.viewer.LoginAct;
import com.esun.rabbit2.viewer.mainact.hemaicenteragp.SportteryBasketballHemaiAct;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.sportterybasketballapg.SportteryBasketballChooseAct;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.sportterybasketballapg.SportteryBasketballChooseList;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.LotteryInfoListFootball;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.LotteryRecordBasketballAct;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: SportteryFootballAgp
 * @Description: (竞彩篮球ActivityGroup)
 * @author: City Jiangsy@500wan.com
 * @date: 2011-8-12 上午10:32:09
 * 
 */
public class SportteryBasketballAgp extends ActivityGroup implements OnClickListener, OnTabChangeListener {

	private TabHost sportteryBasketballTabHostMain;
	private ImageButton btnSportteryBasketballAgpCancel;
	private ImageButton btnSportteryBasketballAgpMenu;
	private ImageButton btnSportteryBasketballAgpFilter;
	// private TextView tvTitle;

	private static final String TAB_CHOOSE = "0";
	private static final String TAB_HEMAI = "1";
	private static final String TAB_LOTTERY_RECORD = "2";
	private static final String TAB_LOTTER_INFO = "3";
	private static final String TAB_INTRODACTION = "4";

	private Dialog menuDialog = null;
	private Button menuBtnChoose;
	private Button menuBtnHemai;
	private Button menuBtnLotteryRecord;
	private Button menuBtnZhuihaoRecord;
	private Button menuBtnLotteryInfo;
	private Button menuBtnIntroduction;
	private LinearLayout linearMenuBg;
	private TextView tvTitle;

	private int CURRENT_TAB_NUM;
	private Bundle bundleSetCurrentTab;

	public static Handler handlerSportteryBasketballAgp;
	public static final int IN_CHOOSE_VIEW = 10001;
	public static final int IN_LIST_VIEW = 10002;
	public static final int SHOW_FILTER = 10003;
	public static final int NO_FILTER = 10004;

	// 精彩足球开奖信息选择日期按钮所需数据
	/** ======================start================= */
	private int mYear;
	private int mMonth;
	private int mDay;
	private int currentYear;
	private int currentMonth;
	private int currentDay;
	private Handler handler;
	private static final int GET_SERVERTIME_SUCCEED = 10005;
	private static final int GET_SERVERTIME_FAILED = 10006;
	private static final int DATE_DIALOG_ID = 1;
	private GetServerTimeCommunicater timeCommunicater;
	private boolean isStop = false;// 若获取失败，是否继续获取当前时间
	private ImageButton btnDateChoose;
	private boolean isExcute = false;// 是否获取过服务器时间

	/** ======================end================= */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sportterybasketball_agp);

		bundleSetCurrentTab = this.getIntent().getExtras();
		CURRENT_TAB_NUM = bundleSetCurrentTab.getInt("CURRENT_TAB_NUM");
		EDebug.o(this, "set currentTab " + CURRENT_TAB_NUM);
		handlerInit();
		initHandler();// 开奖信息用handler
		uiInIt();
	}

	private void handlerInit() {
		handlerSportteryBasketballAgp = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case IN_CHOOSE_VIEW:
					tvTitle.setText("竞彩篮球胜负投注");
					btnSportteryBasketballAgpFilter.setVisibility(View.VISIBLE);
					break;

				case IN_LIST_VIEW:
					tvTitle.setText("竞彩篮球胜负投注列表");
					btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
					break;

				case SHOW_FILTER:
					btnSportteryBasketballAgpFilter.setImageResource(R.drawable.icon_pressed_pickteam_sx_42x48);
					break;

				case NO_FILTER:
					btnSportteryBasketballAgpFilter.setImageResource(R.drawable.icon_default_pickteam_sx_33x40);
					break;
				default:
					break;
				}
			}
		};
	}

	private void uiInIt() {
		tabInit();
		btnSportteryBasketballAgpCancel = (ImageButton) findViewById(R.id.sportterybasketballagp_btn_cancel);
		btnSportteryBasketballAgpCancel.setOnClickListener(this);
		btnSportteryBasketballAgpMenu = (ImageButton) findViewById(R.id.sportterybasketballagp_btn_menu);
		btnSportteryBasketballAgpMenu.setOnClickListener(this);
		btnSportteryBasketballAgpFilter = (ImageButton) findViewById(R.id.sportterybasketballagp_btn_filter);
		btnSportteryBasketballAgpFilter.setOnClickListener(this);
		btnDateChoose = (ImageButton) findViewById(R.id.sportterybasketballagp_btn_dateChoose);
		btnDateChoose.setOnClickListener(this);

		tvTitle = (TextView) findViewById(R.id.sportterybasketballagp_tv_title);
		if (CURRENT_TAB_NUM == 0) {
			tvTitle.setText("竞彩篮球胜负投注");
		} else if (CURRENT_TAB_NUM == 1) {
			btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
			tvTitle.setText("竞彩篮球合买列表");
		}

	}

	private void tabInit() {
		sportteryBasketballTabHostMain = (TabHost) findViewById(R.id.sportterybasketballagp_tabhost_main);
		sportteryBasketballTabHostMain.setup(SportteryBasketballAgp.this.getLocalActivityManager());

		TabSpec ts0 = sportteryBasketballTabHostMain.newTabSpec(TAB_CHOOSE);
		ts0.setIndicator("");
		ts0.setContent(new Intent(this, SportteryBasketballChooseAct.class));
		sportteryBasketballTabHostMain.addTab(ts0);

		TabSpec ts1 = sportteryBasketballTabHostMain.newTabSpec(TAB_HEMAI);
		ts1.setIndicator("");
		ts1.setContent(new Intent(this, SportteryBasketballHemaiAct.class));
		sportteryBasketballTabHostMain.addTab(ts1);

		TabSpec ts2 = sportteryBasketballTabHostMain.newTabSpec(TAB_LOTTERY_RECORD);
		ts2.setIndicator("");
		ts2.setContent(new Intent(this, LotteryRecordBasketballAct.class));
		sportteryBasketballTabHostMain.addTab(ts2);

		TabSpec ts3 = sportteryBasketballTabHostMain.newTabSpec(TAB_LOTTER_INFO);
		ts3.setIndicator("");
		ts3.setContent(new Intent(this, LotteryInfoListFootball.class).putExtra("lotid", Config.JINGCAILANQIU));
		sportteryBasketballTabHostMain.addTab(ts3);

		TabSpec ts4 = sportteryBasketballTabHostMain.newTabSpec(TAB_INTRODACTION);
		ts4.setIndicator("");
		ts4.setContent(new Intent(this, HelpAct.class).putExtra("url", Config.SPORTTERYBASKETBALL_INTRODUCE_WEB_ADD).putExtra("title", Config.NULLMARK).putExtra("havetitle", Config.NUM0));
		sportteryBasketballTabHostMain.addTab(ts4);

		sportteryBasketballTabHostMain.setCurrentTab(CURRENT_TAB_NUM);
		sportteryBasketballTabHostMain.setOnTabChangedListener(this);
	}

	private void setMenuDialog() {
		menuDialog = new Dialog(this, R.style.dialogNoFloating);
		menuDialog.getWindow().setContentView(R.layout.shuangseqiuagp_dialog_menu);

		menuBtnChoose = (Button) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_btn_choose);
		menuBtnChoose.setOnClickListener(this);

		menuBtnHemai = (Button) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_btn_hemai);
		menuBtnHemai.setOnClickListener(this);

		menuBtnLotteryRecord = (Button) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_btn_lotteryRecord);
		menuBtnLotteryRecord.setOnClickListener(this);

		menuBtnZhuihaoRecord = (Button) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_btn_zhuihaoRecord);
		// menuBtnZhuihaoRecord.setOnClickListener(this);
		menuBtnZhuihaoRecord.setVisibility(View.GONE);
		ImageView imgZhuihao = (ImageView) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_img_zhuihao);
		imgZhuihao.setVisibility(View.GONE);

		menuBtnLotteryInfo = (Button) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_btn_lotteryInfo);
		menuBtnLotteryInfo.setOnClickListener(this);

		menuBtnIntroduction = (Button) menuDialog.getWindow().findViewById(R.id.shuangseqiuagpdialogmenu_btn_introduction);
		menuBtnIntroduction.setOnClickListener(this);

		linearMenuBg = (LinearLayout) menuDialog.getWindow().findViewById(R.id.shuangseqiuagp_dialog_menu_linear_bg);
		linearMenuBg.setOnClickListener(this);

		menuDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub

			}
		});

		menuDialog.show();

	}

	@Override
	public void onClick(View v) {

		Message msgRefresh = new Message();
		msgRefresh.what = Config.DO_REFRESH;

		switch (v.getId()) {
		case R.id.sportterybasketballagp_btn_cancel:
			SportteryBasketballAgp.this.finish();
			break;

		case R.id.sportterybasketballagp_btn_menu:
			setMenuDialog();
			break;

		case R.id.sportterybasketballagp_btn_filter:
			Message msg = SportteryBasketballChooseList.handlerChoosePage.obtainMessage(SportteryBasketballChooseList.DO_FILTER, null);
			SportteryBasketballChooseList.handlerChoosePage.sendMessage(msg);
			break;

		case R.id.shuangseqiuagpdialogmenu_btn_choose:
			sportteryBasketballTabHostMain.setCurrentTab(0);
			menuDialog.dismiss();
			break;

		case R.id.shuangseqiuagpdialogmenu_btn_hemai:
			btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
			// SportteryBasketballHemaiAct.showType = 0;
			sportteryBasketballTabHostMain.setCurrentTab(1);
			menuDialog.dismiss();
			break;

		case R.id.shuangseqiuagpdialogmenu_btn_lotteryRecord:
			if (isLogin()) {
				btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
				sportteryBasketballTabHostMain.setCurrentTab(2);
				LotteryRecordBasketballAct.handlerGetBasketballLotteryRecord.sendMessage(msgRefresh);
			} else {
				startActivity(new Intent(SportteryBasketballAgp.this, LoginAct.class));
			}
			menuDialog.dismiss();
			break;

		case R.id.shuangseqiuagpdialogmenu_btn_lotteryInfo:

			btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
			if (!isExcute) {
				getCurrentServerTimeThread();
				isExcute = true;
			}
			sportteryBasketballTabHostMain.setCurrentTab(3);
			menuDialog.dismiss();
			break;

		case R.id.shuangseqiuagpdialogmenu_btn_introduction:
			btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
			sportteryBasketballTabHostMain.setCurrentTab(4);
			menuDialog.dismiss();
			break;

		case R.id.shuangseqiuagp_dialog_menu_linear_bg:
			menuDialog.dismiss();
			break;

		case R.id.sportterybasketballagp_btn_dateChoose:

			SportteryBasketballAgp.this.showDialog(DATE_DIALOG_ID);

			break;

		default:
			break;
		}
	}

	private boolean isLogin() {
		if (UserInfo.getUserInfo().getUserSession().length() > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onTabChanged(String tabId) {

		int index = Integer.valueOf(tabId);

		// 判断是否显示期号选择按钮、
		if (index == 3) {
			btnDateChoose.setVisibility(View.VISIBLE);
		} else {
			btnDateChoose.setVisibility(View.GONE);
		}

		switch (Integer.valueOf(tabId)) {
		case 0:
			if (((SportteryChooseActivity) sportteryBasketballTabHostMain.getCurrentView().getContext()).getCurrentPageFlag() == 0) {
				tvTitle.setText("竞彩篮球胜负投注");
				btnSportteryBasketballAgpFilter.setVisibility(View.VISIBLE);
			} else if (((SportteryChooseActivity) sportteryBasketballTabHostMain.getCurrentView().getContext()).getCurrentPageFlag() == 1) {
				tvTitle.setText("竞彩篮球胜负投注列表");
				btnSportteryBasketballAgpFilter.setVisibility(View.GONE);
			}
			break;

		case 1:
			tvTitle.setText("竞彩篮球胜负合买列表");
			break;

		case 2:
			tvTitle.setText("竞彩篮球胜负购彩记录");
			break;

		case 3:
			tvTitle.setText("竞彩篮球胜负开奖信息");
			break;

		case 4:
			tvTitle.setText("竞彩篮球胜负玩法介绍");
			break;

		default:
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			setMenuDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onTrackballEvent(MotionEvent event) {
		return true;
	}

	/** ======================start================= */

	// 获取本地当前日期
	private void getLocalDate() {
		final Calendar c = Calendar.getInstance();
		updateCurrentTime(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
		EDebug.o(this, currentYear + "-" + currentMonth + "-" + currentDay);
	}

	// 更新当前日期
	private void updateCurrentTime(int year, int month, int day) {
		EDebug.o(this, "更新当前日期" + year + "-" + month + "-" + day);
		currentYear = year;
		currentMonth = month;
		currentDay = day;

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			EDebug.o(this, "生成dialog" + currentYear + "-" + currentMonth + "-" + currentDay);
			CustomDatePicker datePicker = new CustomDatePicker(this, mDateSetListener, currentYear, currentMonth - 1, currentDay);
			return datePicker;
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID:
			// EDebug.o(this, "准备dialog" + currentYear + "-" + currentMonth + "-" + currentDay);
			// if (mYear == 0 || (mMonth + 1) == 0 || mDay == 0) {
			// ((DatePickerDialog) dialog).updateDate(currentYear, currentMonth - 1, currentDay);
			// } else {
			// ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			// }
			break;
		}
	}

	// 向竞彩足球开奖信息发送日期
	private void sendDateInfo() {
		EDebug.o(this, mYear + "-" + mMonth + "-" + mDay);
		mMonth = mMonth + 1;
		if (isDateEnable(mYear, mMonth, mDay)) {
			Message msg = new Message();
			Hashtable<String, String> map = new Hashtable<String, String>();
			map.put("year", String.valueOf(mYear));
			if (mMonth >= 10) {
				map.put("month", String.valueOf(mMonth));
			} else {
				map.put("month", "0" + String.valueOf(mMonth));
			}
			if (mDay >= 10) {
				map.put("day", String.valueOf(mDay));
			} else {
				map.put("day", "0" + String.valueOf(mDay));
			}
			EDebug.o(this, map.get("year") + "-" + map.get("month") + "-" + map.get("day"));
			map.put(Key.KEY_LOTID, Config.JINGCAILANQIU);
			msg = LotteryInfoListFootball.handler.obtainMessage(LotteryInfoListFootball.DATE_CHANGED, map);
			LotteryInfoListFootball.handler.sendMessage(msg);
		} else {
			ViewerUtil.showTipDialog(SportteryBasketballAgp.this, getResources().getString(R.string.date_error), false);
		}
	}

	// 判断所选日期是不是超出范围
	private boolean isDateEnable(int year, int month, int day) {

		String[] strStartingDate = Config.FOOTBALL_LOTTERYINFO_STARTINGDATE.split("-");

		int startingYear = Integer.valueOf(strStartingDate[0]);
		int startingMonth = Integer.valueOf(strStartingDate[1]);
		int startingDay = Integer.valueOf(strStartingDate[2]);

		if (mYear > currentYear || mYear < startingYear) {
			EDebug.o(this, "所选年份超出范围" + mYear + "===" + mMonth + "===" + mDay + "错误");
			return false;
		} else if (mYear == startingYear) {
			if (mMonth < startingMonth) {
				EDebug.o(this, "所选年份为初始年份时,所选月份小于初始月份" + mYear + "===" + mMonth + "===" + mDay + "错误");
				return false;
			} else if (mMonth == startingMonth) {
				if (mDay < startingDay) {
					EDebug.o(this, "所选年份为初始年份,所选月份为始月份,所选日小于初始日" + mYear + "===" + mMonth + "===" + mDay + "错误");
					return false;
				} else {
					EDebug.o(this, "所选年份为初始年份,所选月份为始月份,所选日大于等于初始日" + mYear + "===" + mMonth + "===" + mDay + "正确");
					return true;
				}
			} else {
				EDebug.o(this, "所选年份为初始年份,所选月份大于初始月份" + mYear + "===" + mMonth + "===" + mDay + "正确");
				return true;
			}
		} else if (mYear == currentYear) {
			if (mMonth > currentMonth) {
				EDebug.o(this, "所选年份为当前年份,所选月份大于当前月份" + mYear + "===" + mMonth + "===" + mDay + "错误");
				return false;
			} else if (mMonth == currentMonth) {
				if (mDay >= currentDay) {
					EDebug.o(this, "所选年份为当前年份,所选月份等于当前月份,所选日大于等于当前日" + mYear + "===" + mMonth + "===" + mDay + "错误");
					return false;
				} else {
					EDebug.o(this, "所选年份为当前年份,所选月份等于当前月份,所选日小于当前日" + mYear + "===" + mMonth + "===" + mDay + "正确");
					return true;
				}
			} else {
				EDebug.o(this, "所选年份为当前年份,所选月份小于当前月份" + mYear + "===" + mMonth + "===" + mDay + "正确");
				return true;
			}
		} else {
			EDebug.o(this, "所选年份在区间范围内" + mYear + "===" + mMonth + "===" + mDay + "正确");
			return true;
		}
	}

	// 点击设置事件响应
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			sendDateInfo();
		}

	};

	// 重写DatePickerDialog，改变按钮文字
	private class CustomDatePicker extends DatePickerDialog {

		public CustomDatePicker(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
			super(context, callBack, year, monthOfYear, dayOfMonth);
			setButton("确定", this);
			setButton2("取消", (OnClickListener) null);
		}
	}

	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_SERVERTIME_SUCCEED:

					EDebug.o(SportteryBasketballAgp.this, "get time succeed");
					ServerCurrentTimeInfo timeInfo = timeCommunicater.getCurrentServerTime();
					String[] strDate = timeInfo.getServerDate().split("-");
					updateCurrentTime(Integer.valueOf(strDate[0]), Integer.valueOf(strDate[1]), Integer.valueOf(strDate[2]));
					isStop = false;

					break;

				case GET_SERVERTIME_FAILED:

					// 暂用本地时间,3秒后重新获取服务器时间
					EDebug.o(SportteryBasketballAgp.this, "get time succeed failed == delay");
					getLocalDate();
					delayThread();

					break;

				case DELAY_FINISH:

					EDebug.o(SportteryBasketballAgp.this, "get time again");
					if (isStop) {
						getCurrentServerTimeThread();
					}

					break;

				default:
					break;
				}
			}
		};
	}

	// 获取当前服务器时间
	private void getCurrentServerTimeThread() {
		new Thread() {

			@Override
			public void run() {
				super.run();
				if (timeCommunicater == null) {
					timeCommunicater = new GetServerTimeCommunicater();
				}
				try {
					boolean isSucceed = timeCommunicater.isGetServerTimeSucceed();
					if (isSucceed) {
						Message msg = handler.obtainMessage(GET_SERVERTIME_SUCCEED, null);
						handler.sendMessage(msg);
					} else {
						Message msg = handler.obtainMessage(GET_SERVERTIME_FAILED, null);
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage(Config.CONNECTION_FAIL, null);
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

	// 延迟3秒线程
	private static final int DELAY_FINISH = 10003;

	private void delayThread() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					sleep(3000);
					EDebug.o(SportteryBasketballAgp.this, "delay 3");
					Message msg = new Message();
					msg = handler.obtainMessage(DELAY_FINISH, null);
					handler.sendMessage(msg);
				} catch (Exception e) {

				}
			}
		}.start();
	}

	/** ======================start================= */

}
